package gspringboot

import (
	"context"
	"gitee.com/hongzhaomin/gspring/iface"
	"gitee.com/hongzhaomin/hzm-common-go/streams"
	"gitee.com/hongzhaomin/hzm-common-go/toolkit"
	"os"
	"path/filepath"
	"strings"
	"time"
)

var _ ApplicationRunListener = (*LogListener)(nil)

type LogListener struct {
	cancel context.CancelFunc
}

func (my *LogListener) Ready(_ iface.ApplicationContext, environment ConfigurationEnvironment, logger iface.GspringLogger) {
	// 创建一个取消上下文
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	my.cancel = cancel
	// 启动日志滚动删除协程
	go func() {
		logFile := environment.GetStringReplacePlaceholders(logFilePropName)
		if logFile == "" {
			return
		}

		//ticker := time.NewTicker(2 * time.Hour)
		ticker := time.NewTicker(2 * time.Second)
		defer ticker.Stop()
		for {
			select {
			case <-ticker.C:
				logFileKeepDays := environment.GetInt(logFileKeepDaysPropName)
				if logFileKeepDays <= 0 {
					break
				}
				currentTime := time.Now()
				var keepFileKeywords []string
				for i := 1; i < logFileKeepDays; i++ {
					keepFileKeywords = append(keepFileKeywords,
						currentTime.AddDate(0, 0, 0-i).Format("20060102"))
				}

				fileName := filepath.Base(logFile) // xxx.log
				dir := strings.ReplaceAll(logFile, fileName, "")
				seekFiles, err := toolkit.FindFiles(filepath.Dir(dir))
				if err != nil {
					logger.Error("Failed to find log files in %s", dir)
					break
				}
				for _, fName := range seekFiles { // xxx.log
					f := filepath.Join(dir, fName)
					if fileName != fName && streams.OfSlice(keepFileKeywords).NoneMatch(func(s string) bool {
						return strings.Contains(fName, s)
					}) {
						if err = os.Remove(f); err != nil {
							logger.Error("Failed to remove file %s", f)
						}
					}
				}
			case <-ctx.Done():
				return
			}
		}
	}()
}

func (my *LogListener) Shutdown() {
	my.cancel()
}

func (my *LogListener) Starting(_ ConfigurationEnvironment, _ iface.GspringLogger) {

}

func (my *LogListener) ContextPrepared(_ iface.ApplicationContext, _ ConfigurationEnvironment, _ iface.GspringLogger) {

}

func (my *LogListener) Stared(_ iface.ApplicationContext, _ ConfigurationEnvironment, _ iface.GspringLogger) {

}
